package com.zj.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zj.dao.CategoryMapper;
import com.zj.dao.ProductMapper;
import com.zj.model.Category;
import com.zj.model.Product;
import com.zj.restApi.FileUploadApi;
import com.zj.restApi.IdGenratorApi;
import com.zj.web.bean.CategoryDTO;
import com.zj.web.bean.ProductDTO;
import com.zj.web.bean.ResponseResult;
import lombok.AllArgsConstructor;
import lombok.extern.java.Log;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
@Log
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
    private final ProductMapper productMapper;
    //方案三：利用Feign客户端
    @Autowired
    private IdGenratorApi idGenratorApi;
    @Autowired
    private FileUploadApi fileUploadApi;

    @Override
    @Transactional
    public ProductDTO addProduct(ProductDTO productDTO) {


//1.调用 idGenerator 服务 取出id号
        ResponseEntity<ResponseResult<Long>> responseEntity = idGenratorApi.getNextId();  //jdk动态代理对象
        if(responseEntity.getStatusCode()!= HttpStatus.OK || responseEntity.getBody()==null){
            throw new RuntimeException("调用idGenerator服务失败");
        }
        ResponseResult<Long> responseResult = responseEntity.getBody();
        log.info(responseResult.toString());
        if (responseResult == null || responseResult.getCode() != 1) {
            throw new RuntimeException("调用idGenerator服务失败");
        }
        Long id = responseResult.getData();
        productDTO.setProductId(id);

//        文件上传  利用Feign客户端
        ResponseEntity<ResponseResult> responseEntity1 = this.fileUploadApi.uploadFile(new MultipartFile[]{productDTO.getProductImgFile()});
        if(responseEntity1.getStatusCode()!= HttpStatus.OK || responseEntity1.getBody()==null){
            throw new RuntimeException("调用fileUpload服务失败");
        }
        ResponseResult responseResult1 = responseEntity1.getBody();
        log.info(responseResult1.toString());
        if (responseResult1 == null || responseResult1.getCode() != 1) {
            throw new RuntimeException("调用fileUpload服务失败");
        }
        List<String> urls=(List<String>) responseResult1.getData();
        productDTO.setProductImg( urls.get(0) );
        productDTO.setProductStatus(PRODUCT_STATUS_NORMAL);

        // 3. 将 ProductDTO 转换为 Product 实体对象
        Product product = new Product();
        // 使用 Spring 的 BeanUtils 拷贝同名属性
        // 这会将 ProductDTO 中与 product 属性名相同且类型兼容的值拷贝过去
        //                      productDTO   product Model
        BeanUtils.copyProperties(productDTO, product);

        // 4. 执行数据库插入操作，传入的是 Product 实体对象
        Boolean flag = this.save(product);
        if(!flag){
            throw new RuntimeException("添加失败");
        }

        return productDTO;
    }

    //查询特价商品
    @Override
    public List<ProductDTO> getSpecialProducts(Integer product_status) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.apply("price < originalPrice");
        wrapper.eq(Product::getProductStatus,1);
        return productMapper.selectList(wrapper).stream().map(product -> {
            ProductDTO productDTO = new ProductDTO();
            BeanUtils.copyProperties(product, productDTO);
            return productDTO;
        }).collect(Collectors.toList());
    }

    //根据状态查询产品,逆序输出
    @Override
    public List<ProductDTO> getAllProducts(Integer product_status) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        if (product_status!=null && product_status!=-1){
            wrapper.eq(Product::getProductStatus,product_status);
        }
        wrapper.orderByDesc(Product::getProductId);
        return productMapper.selectList(wrapper).stream().map(product -> {
            ProductDTO productDTO = new ProductDTO();
            BeanUtils.copyProperties(product, productDTO);
            return productDTO;
        }).collect(Collectors.toList());
    }

    //根据id查询产品
    @Override
    public ProductDTO getProductById(Long product_id) {
        Product product = productMapper.selectById(product_id);
        ProductDTO productDTO = new ProductDTO();
        BeanUtils.copyProperties(product, productDTO);
        return productDTO;
    }

    //根据分类id查询产品
    @Override
    public List<ProductDTO> getProductsByCategoryId(Long category_id) {
        //且状态为上架
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getCategoryId,category_id);
        wrapper.eq(Product::getProductStatus,1);
        return productMapper.selectList(wrapper).stream().map(product -> {
            ProductDTO productDTO = new ProductDTO();
            BeanUtils.copyProperties(product, productDTO);
            return productDTO;
        }).collect(Collectors.toList());
    }
    //根据id修改产品状态
    @Override
    @Transactional
    public ProductDTO updateProductStatus(Long product_id, Integer product_status) {
        Product product = productMapper.selectById(product_id);
        product.setProductStatus(product_status);
        productMapper.updateById(product);
        ProductDTO productDTO = new ProductDTO();
        BeanUtils.copyProperties(product, productDTO);
        return productDTO;
    }

    //根据id修改产品
    @Override
    @Transactional
    public ProductDTO updateProduct( ProductDTO productDTO) {
        //判断分类是否存在
        Product product1 = productMapper.selectById(productDTO.getProductId());
        if(product1==null){
            throw new RuntimeException("产品不存在"+productDTO.getProductId());
        }
        //更新产品信息
        if (productDTO.getProductImgFile()!=null){
            //文件上传  利用Feign客户端
            ResponseEntity<ResponseResult> responseEntity1 = this.fileUploadApi.uploadFile(new MultipartFile[]{productDTO.getProductImgFile()});
            if(responseEntity1.getStatusCode()!= HttpStatus.OK || responseEntity1.getBody()==null){
                throw new RuntimeException("调用fileUpload服务失败");
            }
            ResponseResult responseResult1 = responseEntity1.getBody();
            log.info(responseResult1.toString());
            if (responseResult1 == null || responseResult1.getCode() != 1) {
                throw new RuntimeException("调用fileUpload服务失败");
            }
            List<String> urls=(List<String>) responseResult1.getData();
            productDTO.setProductImg( urls.get(0) );
        }
        BeanUtils.copyProperties(productDTO,product1);
        productMapper.updateById(product1);
        //返回更新后的分类信息
        Product product2 = productMapper.selectById(productDTO.getProductId());

        ProductDTO productDTO1 = new ProductDTO();
        BeanUtils.copyProperties(product2, productDTO1);
        return productDTO1;
    }
    //根据id查询产品详情+分类表
    @Override
    public ProductDTO getProductDetailById(Long product_id) {
        ProductDTO productDTO = productMapper.selectProductById(product_id);
        return productDTO;
    }

    //根据产品名字查询
    @Override
    public ProductDTO getProductsByName(String productName) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getProductName,productName);
        Product product = productMapper.selectOne(wrapper);
        if (product==null){
            return null;
        }
        ProductDTO productDTO = new ProductDTO();
        BeanUtils.copyProperties(product, productDTO);
        return productDTO;
    }

}
